﻿
class  com.embedchat.core.connection.SocketProtocolClass{
	static var 	instanceName:String = new String ("SocketProtocolClass");
	static var instanceOwner:Object = com.embedchat.core.connection.SocketProtocolClass;

	private static var maxMessageLength:Number = 9999;
	
	public static function codeMessage(commandId:Number, message:String):String{
		var codedCommandId:String = codeCommand(commandId);
		var codedMessage:String = codeMessageBody(message);
		if(codedCommandId && codedMessage){
			return codedCommandId+codedMessage;
		}else{
			return null;
		}
	}
	
	private static function codeCommand(commandId:Number):String{
		if(commandId>0 && commandId<100){
			if(commandId>9){
				return commandId.toString();
			}else{
				return "0"+commandId.toString();
			}
		}else{
			return null;
		}
	}
	private static function codeMessageBody(message:String):String{
		var messageLength:Number = message.length;
		if(messageLength<=0){
			return null;
		}
		if(messageLength<maxMessageLength+1){
			return codeMessageBodyLength(messageLength)+message;
		}else{
			return codeMessageBodyLength(maxMessageLength)+ message.substring(0,maxMessageLength);
		}
	}
	private static function codeMessageBodyLength(messageLength:Number):String{
		var codedMessageCharsLength:String = messageLength.toString();
		var maxMessageValue:String = maxMessageLength.toString();

		while(codedMessageCharsLength.length < maxMessageValue.length){
			codedMessageCharsLength = "0"+codedMessageCharsLength;
		}
		return codedMessageCharsLength;
	}	
}